<?php

// 定义函数处理目录映射
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Haozing\FastCore\Utils\Request\Request;
use Hyperf\Context\ApplicationContext;
use Hyperf\Context\Context;
use Hyperf\Guzzle\HandlerStackFactory;
use Hyperf\Logger\LoggerFactory;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Qbhy\HyperfAuth\Authenticatable;
use Qbhy\HyperfAuth\AuthManager;
use function Hyperf\Support\make;
use function Hyperf\Translation\__;

//post请求方法
if (! function_exists('curlPost')) {
    /**
     * @throws Exception
     */
    function curlPost($url, $data = [], $header = [])
    {
        $factory = new HandlerStackFactory();
        $stack = $factory->create();

        $client = make(Client::class, [
            'handler' => $stack,
        ]);
        try {
            return $client->post($url, [
                'form_params' => $data,
                'headers' => $header,
            ]);
        } catch (GuzzleException $e) {
            throw new Exception($e->getMessage());
        }
    }
}
//get请求方法
if (! function_exists('curlGet')) {
    /**
     * @throws Exception
     */
    function curlGet($url, $data = [], $header = [])
    {
        $factory = new HandlerStackFactory();
        $stack = $factory->create();

        $client = make(Client::class, [
            'handler' => $stack,
        ]);
        try {
            return $client->get($url, [
                'query' => $data,
                'headers' => $header,
            ]);
        } catch (GuzzleException $e) {
            throw new Exception($e->getMessage());
        }
    }
}

// 用户密码加密方式，双重md5加盐
if (! function_exists('passwordMd5')) {
    function passwordMd5(string $password): array {
        // 生成六位随机盐
        $salt = substr(md5(uniqid(mt_rand(), true)), 0, 6);
        $hash = md5(md5($password).$salt);
        return [
            'password' => $hash,
            'salt' => $salt,
        ];
    }
}

// 用户密码验证
if (! function_exists('passwordMd5Verify')) {
    function passwordMd5Verify(string $password, string $hash, string $salt): bool {
        if($hash == md5(md5($password).$salt)){
            return true;
        }else{
            return false;
        }
    }
}

//生成不重复的数字大小写字母组成的字符串，可以定义长度
if (! function_exists('randomStr')) {
    function randomStr(int $length = 6): string {
        $str = '';
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str.= $strPol[rand(0, $max)];
        }
        return $str;
    }
}

if (! function_exists('loginUser')) {
    /**
     * 获取后台用户信息
     *
     * @param string|null $field 字段名称
     * @return array|string 用户信息|用户字段信息
     */
    function loginUser(?string $field = null): array|string
    {
        $request = Context::get(ServerRequestInterface::class);
        $resData = $request->getAttribute('user');

        if (! $resData) {
            return [];
        }

        $userData = $request->getAttributes();
        foreach ($userData as $key => $val) {
            if (str_starts_with($key, '_user_')) {
                $resData[substr($key, 6)] = $val;
            }
        }
        $field && $resData = $resData[$field];

        return $resData;
    }
}
if (! function_exists('user')) {
    /**
     * 获取当前登录用户实例
     * @param string $scene
     * @return Authenticatable|null
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    function user(string $scene = 'jwt')
    {
        $guard = container()->get(AuthManager::class)->guard($scene);
        return $guard->user();
    }
}
if (! function_exists('responseDataFormat')) {
    function responseDataFormat($code, string $message = '', array $data = []): array
    {
        return [
            'code' => $code,
            'message'  => $message,
            'data' => $data,
        ];
    }
}

if (! function_exists('t')) {
    /**
     * 多语言函数
     * @param string $key
     * @param array $replace
     * @return string
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    function t(string $key, array $replace = []): string
    {
        return __($key, $replace, lang());
    }
}

if (! function_exists('lang')) {
    /**
     * 获取当前语言
     * @return string
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    function lang(): string
    {
        $acceptLanguage = container()->get(Request::class)->getHeaderLine('accept-language');
        return str_replace('-', '_', !empty($acceptLanguage) ? explode(',',$acceptLanguage)[0] : 'zh_CN');
    }
}

if (! function_exists('container')) {

    /**
     * 获取容器实例
     * @return ContainerInterface
     */
    function container(): ContainerInterface
    {
        return ApplicationContext::getContainer();
    }

}

if (! function_exists("DataReturn")) {
    /**
     * 公共返回数据
     * @param string $msg [提示信息]
     * @param int $code [状态码]
     * @param mixed $data [数据]
     * @return array
     */
    function DataReturn(string $msg = '', int $code = 0, mixed $data = ''): array
    {
        // 默认情况下，手动调用当前方法
        $result = ['message'=>$msg, 'code'=>$code, 'data'=>$data];

        // 错误情况下，防止提示信息为空
        if($result['code'] != 0 && empty($result['msg']))
        {
            $result['msg'] = '操作失败';
        }

        return $result;
    }
}
if (! function_exists('logger')) {

    /**
     * 获取日志实例
     * @param string $name
     * @return LoggerInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    function logger(string $name = 'Log'): LoggerInterface
    {
        return container()->get(LoggerFactory::class)->get($name);
    }

}
if (! function_exists('redis')) {

    /**
     * 获取Redis实例
     * @return \Hyperf\Redis\Redis
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    function redis(): \Hyperf\Redis\Redis
    {
        return container()->get(\Hyperf\Redis\Redis::class);
    }

}

